﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;


namespace ScreenTcpServer
{
    //TCP服务器类
    public class TcpServer
    {
        //监听器
        public TcpListener listener;
        //客户端计数
        public long ClientCount = 0;
        //运行标志
        public bool IsRunning = false;

        //构造方法
        public TcpServer(IPAddress iPAddress, int port)
        {
            listener = new TcpListener(iPAddress, port);
        }

        //启动
        public void Start()
        {
            try
            {
                //启动监听器
                listener.Start();
                //Console.WriteLine($"TCP server started at {listener.LocalEndpoint}.");
                IsRunning = true;

                //循环接收客户端
                while (true)
                {
                    //运行
                    if (IsRunning)
                    {
                        try
                        {
                            //客户端
                            TcpClient client = listener.AcceptTcpClient();
                            //Console.WriteLine("Client connected.");
                            //启动客户端处理线程
                            new Thread(new ParameterizedThreadStart(ClientThread)).Start(client);
                            //客户端计数
                            ClientCount++;
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        //退出
                        break;
                    }
                }
            }
            catch
            {
                return;
            }
        }

        //停止
        public void Stop()
        {
            try
            {
                IsRunning = false;
                //停止监听器
                listener.Stop();
                //Console.WriteLine("TCP server stopped.");
            }
            catch
            {
                return;
            }
        }

        //客户端处理线程
        private void ClientThread(object obj)
        {
            //客户端
            TcpClient client = (TcpClient)obj;
            try
            {
                //网络流
                NetworkStream stream = client.GetStream();
                //读取客户端请求
                ReadRequest(stream);
                //Console.WriteLine("Request:\n" + content);   

                //创建响应头
                string responseHeader = $"HTTP/1.1 200 OK{Environment.NewLine}Content-Type: text/html{Environment.NewLine}Connection: close{Environment.NewLine}{Environment.NewLine}";
                //创建响应体
                string responseBody = HtmlResponse();
                //组合响应数据
                string data = $"{responseHeader}{Environment.NewLine}{responseBody}";

                //发送响应数据
                SendResponse(stream, data);
                //关闭网络流
                stream?.Close();
                //关闭客户端
                client?.Close();
            }
            catch
            {
                client?.Close();
            }
        }

        //读取客户端请求
        private string ReadRequest(NetworkStream stream)
        {
            //内容     
            byte[] array = new byte[1024];
            //读取
            int count = stream.Read(array, 0, array.Length);
            //返回
            return Encoding.ASCII.GetString(array, 0, count);
        }

        //获取响应的HTML内容
        private string HtmlResponse()
        {
            // 构造HTML响应
            string htmlContent = $"<html><head><title>Server Screen</title></head><body><img src=\"data:image/png;base64,{ScreenHelper.ScreenBase64()}\"/></body><script type=\"text/javascript\">setInterval(function(){{location.reload();}}, 1000);</script></html>";
            //返回
            return htmlContent;
        }

        //发送响应数据
        private void SendResponse(NetworkStream stream, string responseData)
        {
            //获取响应数据
            byte[] dataBytes = Encoding.ASCII.GetBytes(responseData);
            //发送响应头数据
            stream.Write(dataBytes, 0, dataBytes.Length);
        }

    }
}
